<?php
class System_Listen
{
	private static $socket = NULL;
	
	public static function run()
	{	
		self::createListenSocket();
		
		while(TRUE)
		{
		    $socket = socket_accept(self::$socket);
		    //Todo:Now it's an single thread server, so we must process the Client Socket here,
		    //I will make it to provide multiple thread, so we will put the Client Socket in an 
		    //safe queue,separate the listening process and work process.
            if(is_callable(array('App_Work', 'main'))){
                $processor = new App_Work();
                $processor->main($socket);
            }else{
                System_Work::main($socket);    
            }
		}
		
		self::destroyListenSocket();
	}
   
	private static function createListenSocket()
	{
		if(!(self::$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp")))){
			$errCode = socket_last_error();
			throw new System_Exception(socket_strerror($errCode), $errCode);
		}
		
		if(!socket_bind(self::$socket, IP, PORT)){
			$errCode = socket_last_error(self::$socket);
			throw new System_Exception(socket_strerror($errCode), $errCode);
		}
		
		if(!socket_listen(self::$socket, MAX_CONNECTION)){
			$errCode = socket_last_error(self::$socket);
			throw new System_Exception(socket_strerror($errCode), $errCode);
		}
		echo "Server start successfully\r\n";
	}
	
	private static function destroyListenSocket()
	{
		socket_close(self::$socket);
		echo "Server end successfully\r\n";
	}
}